<%#
  # carousel : 轮播图对象
  #   *.buttonList : 轮播图项目列表
  #       *.link : 图片链接
  #       *.url : 点击跳转链接 (可选)
  #       *.title : 图片标题 (可选)
  #       *.description : 图片描述 (可选)
#%>
<style>/* 轮播图容器 */
.carousel-container {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%; /* 16:9 宽高比 */
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 轮播图轨道 */
.carousel-track {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

/* 轮播图幻灯片 */
.carousel-slide {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 0.5s ease;
  z-index: 1;
}

.carousel-slide.active {
  opacity: 1;
  z-index: 2;
}

/* 轮播图图片 */
.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

/* 轮播图链接 */
.carousel-link {
  display: block;
  width: 100%;
  height: 100%;
  color: inherit;
  text-decoration: none;
}

/* 轮播图标题和描述 */
.carousel-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0));
  color: #fff;
  text-align: left;
}

.carousel-title {
  margin: 0 0 8px;
  font-size: 1.5rem;
  font-weight: 600;
}

.carousel-description {
  margin: 0;
  font-size: 1rem;
  opacity: 0.9;
}

/* 轮播图控制按钮 */
.carousel-control {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 40px;
  height: 40px;
  background-color: rgba(255, 255, 255, 0.5);
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  opacity: 0;
  transition: all 0.3s ease;
}

.carousel-container:hover .carousel-control {
  opacity: 1;
}

.carousel-control.prev {
  left: 10px;
}

.carousel-control.next {
  right: 10px;
}

.carousel-control:hover {
  background-color: rgba(255, 255, 255, 0.8);
}

.carousel-control:focus {
  outline: 2px solid #007bff;
  outline-offset: 2px;
}

.carousel-control-icon {
  font-size: 18px;
  color: #333;
}

/* 轮播图指示器 */
.carousel-indicators {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
  z-index: 10;
}

.carousel-indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
  border: none;
  cursor: pointer;
  padding: 0;
  transition: all 0.3s ease;
}

.carousel-indicator.active {
  background-color: #fff;
  transform: scale(1.2);
}

.carousel-indicator:hover {
  background-color: rgba(255, 255, 255, 0.8);
}

.carousel-indicator:focus {
  outline: 2px solid #007bff;
  outline-offset: 2px;
}

/* 自动播放控制 */
.carousel-autoplay-control {
  position: absolute;
  bottom: 10px;
  right: 10px;
  width: 30px;
  height: 30px;
  background-color: rgba(0, 0, 0, 0.5);
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  color: #fff;
  font-size: 12px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.carousel-container:hover .carousel-autoplay-control {
  opacity: 1;
}

.carousel-autoplay-control:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.carousel-autoplay-control:focus {
  outline: 2px solid #007bff;
  outline-offset: 2px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .carousel-caption {
    padding: 10px;
  }
  
  .carousel-title {
    font-size: 1.2rem;
  }
  
  .carousel-description {
    font-size: 0.9rem;
  }
  
  .carousel-control {
    width: 30px;
    height: 30px;
  }
}

@media (max-width: 576px) {
  .carousel-caption {
    padding: 8px;
  }
  
  .carousel-title {
    font-size: 1rem;
    margin-bottom: 4px;
  }
  
  .carousel-description {
    font-size: 0.8rem;
  }
  
  .carousel-indicator {
    width: 8px;
    height: 8px;
  }
}

/* 无障碍支持 */
.carousel-live-region {
  position: absolute;
  width: 1px;
  height: 1px;
  margin: -1px;
  padding: 0;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  border: 0;
}

/* 焦点样式 */
.carousel-container *:focus {
  outline: 2px solid #007bff;
  outline-offset: 2px;
}
</style>

<div class="carousel-container" id="carousel-<%= Math.random().toString(36).substr(2, 9) %>">
  <!-- 轮播图主容器 -->
  <div class="carousel-track">
    <% if(carousel && carousel.buttonList) { %>
      <% carousel.buttonList.forEach(function (item, index) { %>
        <div class="carousel-slide <%= index === 0 ? 'active' : '' %>" 
             role="group" 
             aria-roledescription="slide" 
             aria-label="<%= index + 1 %> of <%= carousel.buttonList.length %>">
          <% if(item.url) { %>
            <a href="<%= item.url %>" class="carousel-link" tabindex="<%= index === 0 ? '0' : '-1' %>">
          <% } %>
          
          <img src="<%= item.link %>" 
               alt="<%= item.title || '轮播图片 ' + (index + 1) %>" 
               class="carousel-image"
               loading="<%= index === 0 ? 'eager' : 'lazy' %>">
          
          <% if(item.title || item.description) { %>
            <div class="carousel-caption">
              <% if(item.title) { %>
                <h3 class="carousel-title"><%= item.title %></h3>
              <% } %>
              <% if(item.description) { %>
                <p class="carousel-description"><%= item.description %></p>
              <% } %>
            </div>
          <% } %>
          
          <% if(item.url) { %>
            </a>
          <% } %>
        </div>
      <% }) %>
    <% } %>
  </div>

  <!-- 导航按钮 -->
  <button class="carousel-control prev" aria-label="上一张">
    <span class="carousel-control-icon" aria-hidden="true">&#10094;</span>
  </button>
  <button class="carousel-control next" aria-label="下一张">
    <span class="carousel-control-icon" aria-hidden="true">&#10095;</span>
  </button>

  <!-- 指示器 -->
  <div class="carousel-indicators" role="tablist">
    <% if(carousel && carousel.buttonList) { %>
      <% carousel.buttonList.forEach(function (item, i) { %>
        <button class="carousel-indicator <%= i === 0 ? 'active' : '' %>" 
                role="tab"
                aria-label="显示第 <%= i + 1 %> 张幻灯片"
                aria-selected="<%= i === 0 ? 'true' : 'false' %>"
                tabindex="<%= i === 0 ? '0' : '-1' %>">
        </button>
      <% }) %>
    <% } %>
  </div>

  <!-- 自动播放控制 -->
  <button class="carousel-autoplay-control" aria-label="暂停自动播放">
    <span class="pause-icon" aria-hidden="true">&#10074;&#10074;</span>
    <span class="play-icon" aria-hidden="true" style="display: none;">&#9658;</span>
  </button>
</div>

<!-- 轮播图脚本 -->
<script>
document.addEventListener('DOMContentLoaded', function() {
  // 获取当前轮播图实例的唯一ID
  const carouselId = document.currentScript.parentElement.querySelector('.carousel-container').id;
  const carousel = document.getElementById(carouselId);
  
  if (!carousel) return;
  
  // 获取轮播图元素
  const track = carousel.querySelector('.carousel-track');
  const slides = carousel.querySelectorAll('.carousel-slide');
  const indicators = carousel.querySelectorAll('.carousel-indicator');
  const prevButton = carousel.querySelector('.carousel-control.prev');
  const nextButton = carousel.querySelector('.carousel-control.next');
  const autoplayButton = carousel.querySelector('.carousel-autoplay-control');
  
  // 初始化变量
  let currentIndex = 0;
  let autoplayInterval;
  let isAutoPlaying = true;
  const autoplayDelay = 5000; // 自动播放间隔，单位毫秒
  
  // 初始化轮播图
  function initCarousel() {
    // 设置初始状态
    updateCarousel();
    
    // 启动自动播放
    startAutoplay();
    
    // 添加事件监听器
    prevButton.addEventListener('click', goToPrevSlide);
    nextButton.addEventListener('click', goToNextSlide);
    autoplayButton.addEventListener('click', toggleAutoplay);
    
    // 为指示器添加点击事件
    indicators.forEach((indicator, index) => {
      indicator.addEventListener('click', () => goToSlide(index));
    });
    
    // 键盘导航
    carousel.addEventListener('keydown', handleKeyDown);
    
    // 鼠标悬停时暂停自动播放
    carousel.addEventListener('mouseenter', pauseAutoplay);
    carousel.addEventListener('mouseleave', () => {
      if (isAutoPlaying) startAutoplay();
    });
    
    // 触摸事件支持
    let touchStartX = 0;
    let touchEndX = 0;
    
    carousel.addEventListener('touchstart', (e) => {
      touchStartX = e.changedTouches[0].screenX;
    }, { passive: true });
    
    carousel.addEventListener('touchend', (e) => {
      touchEndX = e.changedTouches[0].screenX;
      handleSwipe();
    }, { passive: true });
    
    function handleSwipe() {
      const swipeThreshold = 50;
      if (touchEndX < touchStartX - swipeThreshold) {
        goToNextSlide();
      } else if (touchEndX > touchStartX + swipeThreshold) {
        goToPrevSlide();
      }
    }
  }
  
  // 更新轮播图状态
  function updateCarousel() {
    // 更新幻灯片
    slides.forEach((slide, index) => {
      slide.classList.toggle('active', index === currentIndex);
      
      // 更新链接的tabindex
      const link = slide.querySelector('.carousel-link');
      if (link) {
        link.setAttribute('tabindex', index === currentIndex ? '0' : '-1');
      }
    });
    
    // 更新指示器
    indicators.forEach((indicator, index) => {
      indicator.classList.toggle('active', index === currentIndex);
      indicator.setAttribute('aria-selected', index === currentIndex ? 'true' : 'false');
      indicator.setAttribute('tabindex', index === currentIndex ? '0' : '-1');
    });
    
    // 宣布给屏幕阅读器
    announceSlideChange();
  }
  
  // 切换到指定幻灯片
  function goToSlide(index) {
    currentIndex = index;
    updateCarousel();
    resetAutoplay();
  }
  
  // 切换到上一张幻灯片
  function goToPrevSlide() {
    currentIndex = (currentIndex - 1 + slides.length) % slides.length;
    updateCarousel();
    resetAutoplay();
  }
  
  // 切换到下一张幻灯片
  function goToNextSlide() {
    currentIndex = (currentIndex + 1) % slides.length;
    updateCarousel();
    resetAutoplay();
  }
  
  // 开始自动播放
  function startAutoplay() {
    if (autoplayInterval) clearInterval(autoplayInterval);
    autoplayInterval = setInterval(goToNextSlide, autoplayDelay);
    
    // 更新控制按钮
    autoplayButton.setAttribute('aria-label', '暂停自动播放');
    autoplayButton.querySelector('.pause-icon').style.display = '';
    autoplayButton.querySelector('.play-icon').style.display = 'none';
  }
  
  // 暂停自动播放
  function pauseAutoplay() {
    if (autoplayInterval) clearInterval(autoplayInterval);
    autoplayInterval = null;
  }
  
  // 重置自动播放计时器
  function resetAutoplay() {
    if (isAutoPlaying) {
      pauseAutoplay();
      startAutoplay();
    }
  }
  
  // 切换自动播放状态
  function toggleAutoplay() {
    isAutoPlaying = !isAutoPlaying;
    
    if (isAutoPlaying) {
      startAutoplay();
    } else {
      pauseAutoplay();
      autoplayButton.setAttribute('aria-label', '开始自动播放');
      autoplayButton.querySelector('.pause-icon').style.display = 'none';
      autoplayButton.querySelector('.play-icon').style.display = '';
    }
  }
  
  // 处理键盘导航
  function handleKeyDown(e) {
    switch (e.key) {
      case 'ArrowLeft':
        goToPrevSlide();
        break;
      case 'ArrowRight':
        goToNextSlide();
        break;
      case 'Home':
        goToSlide(0);
        break;
      case 'End':
        goToSlide(slides.length - 1);
        break;
      case ' ':
        toggleAutoplay();
        break;
    }
  }
  
  // 为屏幕阅读器宣布幻灯片变化
  function announceSlideChange() {
    const liveRegion = carousel.querySelector('.carousel-live-region') || createLiveRegion();
    const currentSlide = slides[currentIndex];
    const slideTitle = currentSlide.querySelector('.carousel-title')?.textContent || '';
    const slideDescription = currentSlide.querySelector('.carousel-description')?.textContent || '';
    
    const announcement = `幻灯片 ${currentIndex + 1} / ${slides.length}${slideTitle ? ': ' + slideTitle : ''}${slideDescription ? '. ' + slideDescription : ''}`;
    liveRegion.textContent = announcement;
  }
  
  // 创建实时区域用于无障碍宣告
  function createLiveRegion() {
    const liveRegion = document.createElement('div');
    liveRegion.className = 'carousel-live-region';
    liveRegion.setAttribute('aria-live', 'polite');
    liveRegion.setAttribute('aria-atomic', 'true');
    liveRegion.style.position = 'absolute';
    liveRegion.style.width = '1px';
    liveRegion.style.height = '1px';
    liveRegion.style.overflow = 'hidden';
    liveRegion.style.clip = 'rect(0, 0, 0, 0)';
    carousel.appendChild(liveRegion);
    return liveRegion;
  }
  
  // 初始化轮播图
  initCarousel();
});
</script>
